package com.golxen.framework.common.server.game.cmd.user.login;

import com.golxen.framework.ClientProtocol;
import com.golxen.framework.GameErrorCode;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.PBPacket.PBPacketUtils;
import com.golxen.framework.common.server.game.cmd.Cmd;
import com.golxen.framework.common.server.game.cmd.Command;
import com.golxen.framework.event.eGamePlayerEventType;
import com.golxen.framework.log.LogMgr;
import com.golxen.framework.user.player.GamePlayer;
import com.golxen.framework.user.player.GamePlayerMgr;
import com.golxen.framework.user.player.PlayerState;
import com.golxen.protojava.LoginProto;
import com.golxen.utils.LogUtil;
import com.golxen.utils.TimeUtils;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = GameProtocol.S_PLAYER_LOGIN, desc = "玩家游戏服确定登录")
public class ServerLoginGameCmd implements Command {

	@Override
	public Tuple execute(ChannelHandlerContext ctx, PBPacket packet) throws Exception {
		GamePlayer player = GamePlayerMgr.getPlayer(packet.getPlayerId());
		int ret = 0;
		if (null == player) {
			ret = GameErrorCode.E_USER_LOGIN_ERROR;
			LogUtil.COMMON.error("LoginGame failed, userId = " + packet.getPlayerId());
			return new Tuple(null, null);
		}

		// TODO: 这个可以做一些错误判断给ret赋值。。

		//登录结果发送
		sendResult(player, ret);

		if (ret == 0) {
			// 每日重置
			LogUtil.COMMON.debug("login.flow.{} reset day", player.getUserId());
			player.resetDay();


			LogUtil.COMMON.debug("login.flow.{} set state on line", player.getUserId());
			// 登陆状态
			player.setState(PlayerState.LOGIN);

			LogUtil.COMMON.debug("login.flow.{} send login message", player.getUserId());
			// 登陆时需要的数据推送
			player.sendLoginMessage();

			player.notifyListener(eGamePlayerEventType.LoginDays.getValue(), 0);

			player.setState(PlayerState.ONLINE);

			updateLoginTime(player);

			// 登录流程完整结束告诉客户端一下
			player.sendPacket(ClientProtocol.U_LOGIN_LAST_MARK, LoginProto.LoginLastMarkMsg.newBuilder());

			// 登录后协议
			player.afterLogin();

			LogMgr.addLogLogin(player.getUserId(), 0);// 登录记录


			LogUtil.COMMON.info("[loginmark] game login {} {} {}", player.getUserId(), ret, "login complete");
		}

		return new Tuple(null, null);
	}


	private void updateLoginTime(GamePlayer player) {
		player.getUserInfo().setLastLoginTime(System.currentTimeMillis() / 1000);
	}

	private static void sendResult(GamePlayer player, int ret) {
		LoginProto.LoginRespMsg.Builder respMsg = LoginProto.LoginRespMsg.newBuilder();
		respMsg.setRet(ret);
		respMsg.setSystemTime(System.currentTimeMillis() / 1000);
		respMsg.setTimeZone(TimeUtils.getDefaultTimeZone());
		PBPacket message = PBPacketUtils.buildMessage(ClientProtocol.U_PLAYER_LOGIN, respMsg);
		GamePlayerMgr.sendPacket(player.getUserId(), message);
	}


}
